package com.ruoyi.web.controller.transaction;

import com.ruoyi.basedata.domain.ConfirmResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SignUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.merchant.domain.MpMerchant;
import com.ruoyi.merchant.service.IMpMerchantService;
import com.ruoyi.transaction.domain.EmptyOrderReqPay;
import com.ruoyi.transaction.domain.EmptyOrderRspPay;
import com.ruoyi.transaction.domain.TransactionPay;
import com.ruoyi.transaction.domain.TransactionPayExport;
import com.ruoyi.transaction.service.ITransactionPayService;
import com.ruoyi.withdrawalParam.domain.PayCheckRsp;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  信息操作处理
 * 
 * @author ruoyi
 * @date 2019-05-07
 */
@Controller
@RequestMapping("/transaction/transactionPay")
public class TransactionPayController extends BaseController
{
	Logger log = LoggerFactory.getLogger(TransactionPayController.class);
    private String prefix = "transaction/transactionPay";
	
	@Autowired
	private ITransactionPayService transactionPayService;
	@Autowired
	private IMpMerchantService merchantService;


	// 支付状态查询URL - 内部
	@Value("${reqUrlConfig.managerCheckPay}")
	private String managerCheckPay;
	// 通知状态查询URL - 内部
	@Value("${reqUrlConfig.managerNotifyPay}")
	private String managerNotifyPay;
	// 支付状态查询URL - 外部
	@Value("${reqUrlConfig.merchantCheckPay}")
	private String merchantCheckPay;
	// 空单URL - 内部
	@Value("${reqUrlConfig.managerPay}")
	private String managerPay;





	
	@RequiresPermissions("transaction:transactionPay:view")
	@GetMapping()
	public String transactionPay()
	{
	    return prefix + "/transactionPay";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("transaction:transactionPay:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(TransactionPay transactionPay)
	{
		startPage();
        List<TransactionPay> list = transactionPayService.selectTransactionPayList(transactionPay);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出列表
	 */
	@RequiresPermissions("transaction:transactionPay:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TransactionPay transactionPay)
    {
    	List<TransactionPay> list = transactionPayService.selectTransactionPayList(transactionPay);
		List<TransactionPayExport> exportList = dataConvert(list);
		ExcelUtil<TransactionPayExport> util = new ExcelUtil<TransactionPayExport>(TransactionPayExport.class);
        return util.exportExcel(exportList, "TransactionPayExport");
    }


	/**
	 * 导出数据转化   分=>元   状态转化
	 */
	public static List<TransactionPayExport> dataConvert(List<TransactionPay> list) {
		List<TransactionPayExport> exportList = new ArrayList<>();
		for (TransactionPay transactionPay : list) {
			TransactionPayExport transactionPayExport = new TransactionPayExport();
			BeanUtils.copyProperties(transactionPay, transactionPayExport);
			BigDecimal yuan = new BigDecimal("100");
			// 支付金额
			transactionPayExport.setFee(transactionPay.getFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 申请金额
			transactionPayExport.setSubFee(transactionPay.getSubFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 渠道入账
			transactionPayExport.setChFee(transactionPay.getChFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 商户入账
			transactionPayExport.setMchFee(transactionPay.getMchFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 财务入账
			transactionPayExport.setFinFee(transactionPay.getFinFee().divide(yuan,2, BigDecimal.ROUND_HALF_UP));
			// 状态转化
			if (transactionPay.getStatus() == 1) {
				transactionPayExport.setPayStatus("下单失败");
			}else if (transactionPay.getStatus() == 2) {
				transactionPayExport.setPayStatus("下单超时");
			}else if (transactionPay.getStatus() == 3) {
				transactionPayExport.setPayStatus("待支付");
			}else if (transactionPay.getStatus() == 4) {
				transactionPayExport.setPayStatus("未支付");
			}else if (transactionPay.getStatus() == 5) {
				transactionPayExport.setPayStatus("已支付");
			}

			if (transactionPay.getStatus() == 4 || transactionPay.getStatus() == 5) {
				if (transactionPay.getMerchantNotifyStatus() == 0) {
					transactionPayExport.setNotifyStatus("未通知");
				}else if (transactionPay.getMerchantNotifyStatus() == 1) {
					transactionPayExport.setNotifyStatus("已通知");
				}

			}else {
				transactionPayExport.setNotifyStatus("无效");
			}

			exportList.add(transactionPayExport);
		}
		return exportList;
	}


	/**
	 * 新增
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存
	 */
	@RequiresPermissions("transaction:transactionPay:add")
	@Log(title = "", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(TransactionPay transactionPay)
	{		
		return toAjax(transactionPayService.insertTransactionPay(transactionPay));
	}

	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Long id, ModelMap mmap)
	{
		TransactionPay transactionPay = transactionPayService.selectTransactionPayById(id);
		mmap.put("transactionPay", transactionPay);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存
	 */
	@RequiresPermissions("transaction:transactionPay:edit")
	@Log(title = "", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(TransactionPay transactionPay)
	{
		return toAjax(transactionPayService.updateTransactionPay(transactionPay));
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("transaction:transactionPay:remove")
	@Log(title = "", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(transactionPayService.deleteTransactionPayByIds(ids));
	}


	/**
	 * 支付状态查询
	 * @param id			记录id
	 * @return				结果
	 * @throws IOException
	 */
	@PostMapping("/payConfirm")
	@ResponseBody
	public AjaxResult payConfirm(Long id) {
		TransactionPay transactionPay = transactionPayService.selectTransactionPayById(id);
		Long merchantId = transactionPay.getMerchantId();
		MpMerchant merchant = merchantService.selectMpMerchantById(merchantId);
		String key = merchant.getSecretKey();
		// 平台编号
		String code = transactionPay.getCode();
		// 商户编号
		String mchCode = transactionPay.getMchCode();
		// 返回结果
		String result;
		// 根据平台编号和商户编号   判断内部请求、外部请求
		if(code == mchCode || mchCode == null || "".equals(mchCode)) {
			// ===================内部==================================
			JSONObject jsonObject = new JSONObject();
			// type  0支付   1代付
			// jsonObject.put("type",0);
			jsonObject.put("code",code);
			String  toJson = jsonObject.toString();
			result = HttpUtils.sendPost(managerCheckPay, toJson, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				ConfirmResult confirmResult = (ConfirmResult) net.sf.json.JSONObject.toBean(jsonObjectResult, ConfirmResult.class);
				if (confirmResult.getStatus() == 0) {
					return AjaxResult.success(confirmResult.getMsg());
				}else {
					return AjaxResult.error(confirmResult.getMsg());
				}
			}else {
				return AjaxResult.error("请求失败!");
			}
		}else {
			//======================== 外部请求===========================
			// 外部请求数据
			String data = "mch_id=" + merchant.getCode() + "&out_trade_no=" + transactionPay.getMchCode();
			// 进行签名
			String sign = SignUtil.getSignReq(data, key);
			data += "&sign=" + sign;
			log.info("请求的报文：" + data);
			result = HttpUtils.sendPost(merchantCheckPay, data, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				PayCheckRsp payCheckRsp = (PayCheckRsp) net.sf.json.JSONObject.toBean(jsonObjectResult, PayCheckRsp.class);
				if (payCheckRsp.getStatus() == 1) {
					return AjaxResult.success("已支付");
				}else {
					return AjaxResult.error("未支付");
				}
			}
			return AjaxResult.error("请求失败!");
		}
	}






	/**
	 * 通知状态查询
	 * @param platFromCode	平台编号
	 * @param type			支付类型    0支付    1代付
	 * @return				结果
	 * @throws IOException
	 */
	@PostMapping("/notifyConfirm")
	@ResponseBody
	public AjaxResult notifyConfirm(String platFromCode,Integer type) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("code",platFromCode);
		// jsonObject.put("type",type);
		String  toJson = jsonObject.toString();
		String result = HttpUtils.sendPost(managerNotifyPay, toJson, false);
		if (StringUtils.isNotEmpty(result)) {
			JSONObject jsonObjectResult = JSONObject.fromObject(result);
			ConfirmResult confirmResult = (ConfirmResult) net.sf.json.JSONObject.toBean(jsonObjectResult, ConfirmResult.class);
			if (confirmResult.getStatus() == 0) {
				return AjaxResult.success(confirmResult.getMsg());
			}else {
				return AjaxResult.error(confirmResult.getMsg());
			}
		}else {
			return AjaxResult.error("请求失败!");
		}
	}


	/**
	 * 空单
	 */
	@GetMapping("/placeOrder")
	public String placeOrder() {
		return prefix + "/placeOrder";
	}


	/**
	 * 提交空单
	 */
	@PostMapping("/emptyOrder")
	@ResponseBody
	public AjaxResult emptyOrder(EmptyOrderReqPay orderReqPay) {
		try {
			String params = JSONObject.fromObject(orderReqPay).toString();
			log.info("请求的报文： " + params);
			String result = HttpUtils.sendPost(managerPay, params, false);
			if (StringUtils.isNotEmpty(result)) {
				JSONObject jsonObjectResult = JSONObject.fromObject(result);
				EmptyOrderRspPay orderRspPay = (EmptyOrderRspPay) net.sf.json.JSONObject.toBean(jsonObjectResult, EmptyOrderRspPay.class);
				if (orderRspPay.getStatus() == 1) {
					return AjaxResult.success(orderRspPay.getMsg());
				}else {
					return AjaxResult.error(orderRspPay.getMsg());
				}
			}
			return AjaxResult.error("请求异常");
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("系统异常");
		}
	}
}
